# Dreams have to come true after all
from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser, request

from comment.models.User import *
from comment.utils.financial_redis import redis_client
from comment.utils.tokens_pyjwt import *


class RegisterUser(Resource):
    """用户的注册"""

    def post(self):
        rp = RequestParser()
        rp.add_argument('phone', required=True)
        rp.add_argument('username', required=True)
        rp.add_argument('password', required=True)
        rp.add_argument('code', required=True)
        rp.add_argument('invite_code')
        # 验证参数
        args = rp.parse_args()
        # 获取参数
        username = args.username
        password = args.password
        phone = args.phone
        code = args.code
        invite_code = args.invite_code
        # 验证用户名是否唯一
        u = User.query.filter(User.username == username).first()
        if u:
            current_app.logger.info('{}:用户已存在,请换一个'.format(username))
            return {'message': '用户名已存在'}, 400

        # 从redis数据库中得到之前保存的验证码
        key = 'registerCode:{}'.format(phone)
        try:
            real_code = redis_client.get(key)
        except ConnectionError as  e:
            current_app.logger.error(e)
            return {"code": 20001, "message": "redis db connect error."}
        # 开始校验
        if not real_code or real_code.decode() != code:
            return {'message': '验证码错误或已失效'}
        # 把用户信息保存到数据库中
        u = User(username=username, pwd=password, phone=phone, onlock=0)
        # 如果有邀请码,则验证一下
        if invite_code:
            self.checkInvite(u, invite_code)
        db.session.add(u)
        db.session.commit()
        # 创建用户,同时创建一个用户账户
        account = Account(userId=u.id)
        db.session.add(account)
        db.session.commit()

        return {'msg': '注册成功'}

    # 验证邀请码
    def checkInvite(self, user, code):
        code = code.strip()
        # 查询是否是用户生成的邀请码
        checkUser = User.query.filter(User.remark == code).first()
        if checkUser:
            user.sumFriends = checkUser.id  # 邀请码有效,登记邀请人的id到账户
            checkUser.accountInfo.discount += 50  # 邀请人增加50代金券


class IsEistPhone(Resource):
    """
    判断手机号是否存在
    """

    def post(self):
        phone = request.json.get('phone')
        user = User.query.filter(User.phone == phone).first()
        if user:
            return {'message': '此手机已注册', 'code': '20001'}
        return {'msg': '此手机可以注册'}


class SmsCode(Resource):
    """
    发送验证码
    """

    def get(self):
        phone = request.args['phone'].strip()
        import random
        code = random.randint(1000, 9999)
        from Financial.resource.user import constants
        redis_client.setex('registerCode:{}'.format(phone), constants.SMS_CODE_EXPIRES, code)
        return {'smsCode': code}


class Login(Resource):
    """
    登录
    """

    def post(self):
        rp = RequestParser()
        rp.add_argument('username', required=True)
        rp.add_argument('password', required=True)
        args = rp.parse_args()
        username = args.username
        password = args.password

        if not all([username, password]):
            return {'message': '数据不完整', 'code': '20001'}
        user = User.query.filter(User.username == username).first()
        if user:
            if user.check_password(password):
                # 用户登录成功后用户的ID生成token,在返回给前端
                token = generate_tokens(user.id)
                current_app.logger.info(verify_tokens(token))
                return {'token': token}
        return {'message': '用户名或者密码错误', 'code': 20001}


class LoginOut(Resource):
    """
    退出登录
    """

    def post(self):
        if g.user_id:
            g.user_id = None
        return {'msg': 'logout Done'}
